import { nextTick } from "../util/next-tick"

export function renderMixin(Vue) {
  Vue.prototype.$nextTick = function (cb) {
    // 1.vue自己的
    // 2.用户自己的 共2个列队
    return nextTick(cb)
  }
  Vue.prototype._c = function () { // 标签
    return createElement(this, ...arguments)
  }
  Vue.prototype._v = function (text) { // 文本
    return createText(text)
  }
  Vue.prototype._s = function (val) { // 变量
    return val == null ? "" : (typeof val === 'object') ? JSON.stringify(val) : val
  }
  Vue.prototype._render = function () {
    let vm = this;
    let render = vm.$options.render
    // console.log('[ vm ] >', vm)
    let vnode = render.call(this);
    return vnode

  }
}
//创建元素
function createElement(vm, tag, date = {}, ...children) {
  let key = date?.key || undefined
  // console.log('[ tag ] >', tag)
  if (isResved(tag)) {
    // console.log('vnode(vm, tag, date,key, children)', vnode(vm, tag, date,key, children))
    return vnode(vm, tag, date,key, children)
  } else {
    // 创建组件
    // 
    const Ctor = vm.$options['component']
    // console.log('[vm.$Ctor  ] >', Ctor)
    // console.log('[ createcomponent(vm, tag, date, children, Ctor) ] >', createcomponent(vm, tag, date, children, Ctor))
    return createcomponent(vm, tag, date, key,children, Ctor)
  }

}
// 创建组件的虚拟dom
function createcomponent(vm, tag, date,key, children, Ctor) {
  if (typeof Ctor == 'object') {
    Ctor = vm.constructor.extend(Ctor) //返回一个子类
  }
  // 添加一个方法
  date.hook = {
    init(vnode) {
      // 创建了一个child 然后在vnode创建了一个componetInstance
      let child = vnode.componetInstance = new vnode.componetOptptions.Ctor({})
      child.$mount()
    }
  }
  // console.log('[ en})] >', vnode('vm','vue-component'+tag,date,undefined,{Ctor,children}))
  return vnode('vm', 'vue-component-' + tag, date, undefined, undefined, undefined, { Ctor, children })
}
//判断当前是不是组件
function isResved(tag) {
  return ['a', 'div', 'b', 'button', 'span', 'input', 'h1', 'ul'].includes(tag)
}
function vnode(vm, tag, date, key, children, text, componetOptptions) {
  return {
    vm, tag, date, key, children, text, componetOptptions
  }
}
// 文本
function createText(text) {
  return vnode(undefined, undefined,undefined,undefined,undefined, text)
}